package com.freecat.xmqgct.face.activity;

import android.support.v7.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.idl.face.platform.FaceConfig;
import com.baidu.idl.face.platform.FaceSDKManager;
import com.baidu.idl.face.platform.FaceStatusEnum;
import com.baidu.idl.face.platform.ILivenessStrategy;
import com.baidu.idl.face.platform.ILivenessStrategyCallback;
import com.baidu.idl.face.platform.ui.FaceSDKResSettings;
import com.baidu.idl.face.platform.ui.utils.CameraUtils;
import com.baidu.idl.face.platform.ui.utils.VolumeUtils;
import com.baidu.idl.face.platform.ui.widget.FaceDetectRoundView;
import com.baidu.idl.face.platform.utils.APIUtils;
import com.baidu.idl.face.platform.utils.Base64Utils;
import com.baidu.idl.face.platform.utils.CameraPreviewUtils;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.freecat.xmqgct.mvp.model.entity.UpdateBean;
import com.google.gson.Gson;
import com.freecat.xmqgct.MainActivity;
import com.freecat.xmqgct.R;
import com.freecat.xmqgct.app.MyApp;
import com.freecat.xmqgct.face.APIService;
import com.freecat.xmqgct.face.Config;
import com.freecat.xmqgct.face.FaceError;
import com.freecat.xmqgct.face.OnResultListener;
import com.freecat.xmqgct.face.bean.AccessToken;
import com.freecat.xmqgct.face.bean.LiveVerifyBean;
import com.freecat.xmqgct.face.bean.RegResult;
import com.freecat.xmqgct.face.util.ImageSaveUtil;
import com.freecat.xmqgct.face.util.ImageUtil;
import com.freecat.xmqgct.face.widget.DefaultDialog;
import com.freecat.xmqgct.mvp.model.entity.LoginBean;
import com.freecat.xmqgct.mvp.presenter.LoginPresenter;
import com.freecat.xmqgct.mvp.ui.activity.AccountLoginActivity;
import com.freecat.xmqgct.mvp.ui.activity.BaseActivity;
import com.freecat.xmqgct.utils.Constant;
import com.freecat.xmqgct.utils.Tools;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import me.jessyan.art.mvp.IView;
import me.jessyan.art.utils.ArtUtils;
import timber.log.Timber;

public class FaceLivenessExpActivity extends BaseActivity<LoginPresenter> implements IView, SurfaceHolder.Callback,
        Camera.PreviewCallback,
        Camera.ErrorCallback,
        VolumeUtils.VolumeCallback,
        ILivenessStrategyCallback {
    public static final String TAG = FaceLivenessExpActivity.class.getSimpleName();
    private DefaultDialog mDefaultDialog;
    private String type, rybh;
    public Context mContext;
    private boolean mUploading = false;
    private LocationClient locationClient;
    private String time;
    private String address;
    private double longitude;
    private double latitude;
    String xmbh = SPUtils.getInstance(Constant.SP_CONFIG).getString(Constant.PROJECT_NUM);
    int count=0;
    String face_error_log_count1;
    SPUtils spUtils;
    /*
    *
    * 当5次验证失败后，就上传错误日志，并让对方跳过
    * */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(com.baidu.idl.face.platform.ui.R.layout.activity_face_liveness_v3100);
        mContext = this;
        System.out.println("测试人脸识别");
        faceCreat();
         spUtils = SPUtils.getInstance(Constant.SP_CONFIG);

//            spUtils.put(Constant.TOKEN, loginBean.getToken());
//        String face_error_log_zero = SPUtils.getInstance(Constant.SP_CONFIG).getString(Constant.face_error_log_zero);
//
//        String NEW_RZRQ = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(new Date());


        face_error_log_count1 = SPUtils.getInstance(Constant.SP_CONFIG).getString(Constant.face_error_log_count);

        if (face_error_log_count1!=null){
            System.out.println("face_error_log_count========="+face_error_log_count1);
        }else {

            count=0;
            spUtils.put(Constant.face_error_log_count,"0");
        }


        type = getIntent().getStringExtra("type");
        if (type == null) {
            rybh = SPUtils.getInstance(Constant.SP_CONFIG).getString(Constant.USER_ID);
//            mPresenter.checkUpdate(me.jessyan.art.mvp.Message.obtain(this, new String[]{rybh}));
        }
        if (type == null) {
            APIService.getInstance().initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
                @Override
                public void onResult(AccessToken result) {

                }

                @Override
                public void onError(FaceError error) {

                }
            }, this, Config.apiKey, Config.secretKey);
        }
        initView();
        initLocationOption();
    }


    public void initView() {
        if ("1".equals(type) || "2".equals(type)) {
            setTitle("人脸验证");
        } else {
            setTitle("人脸登录");
            showLogin(click);
        }
    }

    View.OnClickListener click = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_login_account:
                    ArtUtils.startActivity(AccountLoginActivity.class);
                    break;
                case R.id.tv_to_register:
                    MyApp.setFaceConfig();
//                    ArtUtils.startActivity(FaceRegistActivity.class);


                    break;
            }
        }
    };

    private void initLocationOption() {
//定位服务的客户端。宿主程序在客户端声明此类，并调用，目前只支持在主线程中启动
        locationClient = new LocationClient(getApplicationContext());
//声明LocationClient类实例并配置定位参数
        LocationClientOption locationOption = new LocationClientOption();
        MyLocationListener myLocationListener = new MyLocationListener();
//注册监听函数
        locationClient.registerLocationListener(myLocationListener);
//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        locationOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
//可选，默认gcj02，设置返回的定位结果坐标系，如果配合百度地图使用，建议设置为bd09ll;
        locationOption.setCoorType("bd09ll");
//可选，默认0，即仅定位一次，设置发起连续定位请求的间隔需要大于等于1000ms才是有效的
        locationOption.setScanSpan(3000);
//可选，设置是否需要地址信息，默认不需要
        locationOption.setIsNeedAddress(true);
//可选，设置是否需要地址描述
        locationOption.setIsNeedLocationDescribe(true);
//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        locationOption.setIsNeedLocationDescribe(true);
//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        locationOption.setIsNeedLocationPoiList(true);
//可选，默认false，设置是否开启Gps定位
        locationOption.setOpenGps(true);
        locationClient.setLocOption(locationOption);
        locationClient.start();
    }


    @Nullable
    @Override
    public LoginPresenter obtainPresenter() {
        return new LoginPresenter(ArtUtils.obtainAppComponentFromContext(this));
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            time = location.getTime();
            address = location.getAddress().address;
            longitude = location.getLongitude();
            latitude = location.getLatitude();
            locationClient.stop();
        }
    }

    FaceStatusEnum currentStatus;
    int currentNum = 0;

    @Override
    public void onLivenessCompletion(FaceStatusEnum status, String message, HashMap<String, String> base64ImageMap) {
        if (mIsCompletion) {
            return;
        }
        if (null != currentStatus && currentStatus == status && currentNum > 3) {
            mIsCompletion = true;
            showMessageDialog("活体检测", "超出错误次数！");
            String rybh = SPUtils.getInstance(Constant.SP_CONFIG).getString(Constant.USER_ID);
            if (null != type)
//                mPresenter.CheckIn(me.jessyan.art.mvp.Message.obtain(FaceLivenessExpActivity.this, new String[]{rybh, xmbh, time, String.valueOf(longitude), String.valueOf(latitude), address, "0"}));
            return;
        }
        if (status == FaceStatusEnum.Liveness_Eye || status == FaceStatusEnum.Liveness_Mouth
                || status == FaceStatusEnum.Liveness_HeadUp || status == FaceStatusEnum.Liveness_HeadDown
                || status == FaceStatusEnum.Liveness_HeadLeft || status == FaceStatusEnum.Liveness_HeadRight
                || status == FaceStatusEnum.Liveness_HeadLeftRight) {
            currentStatus = status;
            currentNum++;
        }

        onRefreshView(status, message);
        if (status == FaceStatusEnum.OK) {
            mIsCompletion = true;
            Set<Map.Entry<String, String>> sets = base64ImageMap.entrySet();
            Bitmap bmp = null;
            List<Bitmap> bitmaps = new ArrayList<>();
            for (Map.Entry<String, String> entry : sets) {
                bmp = base64ToBitmap(entry.getValue());
                bitmaps.add(bmp);
            }
            try {
                Bitmap face = bitmaps.get(0);
                final File file = File.createTempFile(UUID.randomUUID().toString() + "", ".jpg");
                ImageUtil.resize(face, file, 200, 200);
                ImageSaveUtil.saveCameraBitmap(FaceLivenessExpActivity.this, face, "head_tmp.jpg");
                APIService.getInstance().verify(new OnResultListener<RegResult>() {
                    @Override
                    public void onResult(RegResult result) {
                        String jsonRes = result.getJsonRes();
                        LiveVerifyBean bean = new Gson().fromJson(jsonRes, LiveVerifyBean.class);
                        if (bean.getResult().getFace_liveness() >= 0.3) {
                            APIService.getInstance().identify(new OnResultListener<RegResult>() {
                                @Override
                                public void onResult(RegResult result) {
                                    deleteFace(file);
                                    if (result == null) {
                                        mUploading = false;
                                        setTips("人脸校验不通过,请确认是否已注册");
                                        return;
                                    }
                                    String res = result.getJsonRes();
                                    double maxScore = 0;
                                    String userId = "";
                                    String userInfo = "";
                                    if (TextUtils.isEmpty(res)) {
                                        return;
                                    }
                                    JSONObject obj = null;
                                    try {
                                        obj = new JSONObject(res);
                                        JSONObject resObj = obj.optJSONObject("result");
                                        if (resObj != null) {
                                            JSONArray resArray = resObj.optJSONArray("user_list");
                                            int size = resArray.length();
                                            for (int i = 0; i < size; i++) {
                                                JSONObject s = (JSONObject) resArray.get(i);
                                                if (s != null) {
                                                    double score = s.getDouble("score");
                                                    if (score > maxScore) {
                                                        maxScore = score;
                                                        userId = s.getString("user_id");
                                                        userInfo = s.getString("user_info");
                                                    }
                                                }
                                            }
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }

                                    if (maxScore > 80) {
                                        if ("1".equals(type) || "2".equals(type)) {
                                            String rybh = SPUtils.getInstance(Constant.SP_CONFIG).getString(Constant.USER_ID);
                                            if (userId.equals(rybh)) {
//                                                if ("1".equals(type)) {
//
//                                                    spUtils.remove(Constant.face_error_log_count);
//                                                    spUtils.put(Constant.face_error_log_count,"0");
//                                                    ArtUtils.startActivity(CheckInActivity.class);
//                                                    finish();
//                                                } else {
//                                                    spUtils.remove(Constant.face_error_log_count);
//                                                    spUtils.put(Constant.face_error_log_count,"0");
//                                                    SPUtils.getInstance(Constant.SP_CONFIG).put(Constant.MUST_VERIFY, false);
//                                                    mPresenter.CheckIn(me.jessyan.art.mvp.Message.obtain(FaceLivenessExpActivity.this, new String[]{rybh, xmbh, time, String.valueOf(longitude), String.valueOf(latitude), address, "1"}));
//                                                }
                                            } else {
                                                setTips("您与当前账号不匹配");
                                                mUploading = false;
                                            }
                                        } else {
                                            spUtils.remove(Constant.face_error_log_count);
                                            spUtils.put(Constant.face_error_log_count,"0");
                                            System.out.println("登录");
                                            setTips(String.format("欢迎%s", userInfo));
//                                            mPresenter.getUserDetail(me.jessyan.art.mvp.Message.obtain(FaceLivenessExpActivity.this, new String[]{userId}));
                                        }


                                    } else {


                                        /*
                                        * 每次先读取缓存的记录
                                        * 读取后+1来判断是否是第5次 如果是第5次，就清零
                                        * */

                                        if (face_error_log_count1!=null){
                                            count=Integer.valueOf(face_error_log_count1);

                                            if (count==5){

                                                spUtils.remove(Constant.face_error_log_count);
                                                spUtils.put(Constant.face_error_log_count,"0");
                                                SPUtils.getInstance(Constant.SP_CONFIG).put(Constant.MUST_VERIFY, false);
//                                                mPresenter.CheckIn(me.jessyan.art.mvp.Message.obtain(FaceLivenessExpActivity.this, new String[]{rybh, xmbh, time, String.valueOf(longitude), String.valueOf(latitude), address, "3"}));

                                            }else {
                                                count=count+1;
                                                face_error_log_count1=String.valueOf(count);
                                                spUtils.remove(Constant.face_error_log_count);
                                                spUtils.put(Constant.face_error_log_count,face_error_log_count1);
                                            }
                                        }


                                        System.out.println("当前人脸检查失败次数===face_error_log_count"+face_error_log_count1);
                                        System.out.println("当前人脸检查失败次数===face_error_log_count"+face_error_log_count1);
                                        setTips("人脸校验不通过,请确认是否已注册");
                                        mUploading = false;
                                    }
                                }

                                @Override
                                public void onError(FaceError error) {
                                    error.printStackTrace();
                                    deleteFace(file);
                                    mUploading = false;
                                    if (error.getErrorCode() == 10000) {
                                        setTips("人脸校验不通过,请检查网络后重试");
                                    } else {
                                        setTips("人脸校验不通过,请确认是否已注册");
                                    }
                                }
                            }, file);
                        } else {
                            /*ToastUtils.showShort("当前不是活体");*/
                            setTips("当前不是活体");
                            mUploading = false;
                        }
                    }

                    @Override
                    public void onError(FaceError error) {
                        String errorMessage = error.getErrorMessage();
                        setTips("活体验证失败");
                        mUploading = false;
                    }
                }, file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (status == FaceStatusEnum.Error_DetectTimeout ||
                status == FaceStatusEnum.Error_LivenessTimeout ||
                status == FaceStatusEnum.Error_Timeout) {
            showMessageDialog("活体检测", "采集超时");
        }
    }

    private void deleteFace(File file) {
        if (file != null && file.exists()) {
            file.delete();
        }
    }

    private void showMessageDialog(String title, String message) {
        if (mDefaultDialog == null) {
            DefaultDialog.Builder builder = new DefaultDialog.Builder(this);
            builder.setTitle(title).
                    setMessage(message).
                    setNegativeButton("确认",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if("1".equals(type) || "2".equals(type)) {
                                        mDefaultDialog.dismiss();
                                    }else{
                                        mDefaultDialog.dismiss();
                                        finish();
                                    }
                                }
                            });
            mDefaultDialog = builder.create();
            mDefaultDialog.setCancelable(false);
        }
        mDefaultDialog.dismiss();
        mDefaultDialog.show();
    }

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    public void showMessage(@NonNull String message) {
        ToastUtils.showShort(message);
    }

    @Override
    public void handleMessage(@NonNull me.jessyan.art.mvp.Message message) {
        switch (message.what) {
            case LoginPresenter.GET_USER_DETAIL:
                LoginBean loginBean = (LoginBean) message.obj;
                if (loginBean != null) {
                    SPUtils spUtils = SPUtils.getInstance(Constant.SP_CONFIG);
                    spUtils.put(Constant.TOKEN, loginBean.getToken());
//                    spUtils.put(Constant.TOKEN, "53bdc6a1-07c4-4aed-a231-d058499a8031");
                    spUtils.put(Constant.USER_ID, loginBean.getRybh());
                    spUtils.put(Constant.ACCOUNT, loginBean.getUsername());
                    spUtils.put(Constant.PASSWORD, loginBean.getPassword());
                    spUtils.put(Constant.USER_NAME, loginBean.getRyxm());
                    spUtils.put(Constant.UNIT_NAME, loginBean.getDwmc());
                    spUtils.put(Constant.ZH_LX, loginBean.getZhlx());
                    spUtils.put(Constant.USER_AVATAR, loginBean.getRytx());
                    List<LoginBean.CslistBean> cslist = loginBean.getCslist();
                    for (LoginBean.CslistBean cslistBean : cslist) {
                        switch (cslistBean.getCsmc()) {
                            case "WDSWSC":
                                spUtils.put(Constant.SWSJ, cslistBean.getCsz());
                                break;
                            case "ZKJLCS":
                                spUtils.put(Constant.ZKJL, cslistBean.getCsz());
                                break;
                            case "RLSBSJCS":
                                spUtils.put(Constant.RLSBSJCS, cslistBean.getCsz());
                                break;
                            case "ZKWZJLCS":
                                spUtils.put(Constant.ZKWZJLCS, cslistBean.getCsz());
                                break;
                        }
                    }
                    ArtUtils.startActivity(MainActivity.class);
                    finish();
                } else {
                    ToastUtils.showShort("没有相关账户信息");
                    mUploading = false;
                }
                break;
            case LoginPresenter.CHECK_IN:
                setResult(RESULT_OK);
                finish();
                break;
            case LoginPresenter.CHECK_UPDATE:
                UpdateBean updateBean = (UpdateBean) message.obj;
                if (updateBean != null) {
                    int appVersionCode = AppUtils.getAppVersionCode();
                    int version = Integer.parseInt(updateBean.getVERSIONCODE());
                    if (version > appVersionCode) {
                        showDialog(updateBean.getAPKURL(), updateBean.getDESCRIPTION());
                    } else {
                        Timber.d("无新版本");
                    }
                } else {
                    ToastUtils.showShort("无新版本");
                }
                break;
        }
    }

    private void showDialog(String apkUrl, String description) {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_update_layout, null);
        TextView tvContent = view.findViewById(R.id.tv_update_content);
        ImageView ivUpdate = view.findViewById(R.id.iv_update);
        ImageView ivClose = view.findViewById(R.id.iv_close);
        AlertDialog alertDialog = new AlertDialog.Builder(this, R.style.DialogStyle).setView(view).show();
        tvContent.setText(description);
        ivUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
                if (apkUrl != null) {
                    Tools.downloadAPK(URLEncoder.encode(apkUrl), mContext);
                }
            }
        });
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
    }

    // View
    protected View mRootView;
    protected FrameLayout mFrameLayout;
    protected SurfaceView mSurfaceView;
    protected SurfaceHolder mSurfaceHolder;
    protected ImageView mCloseView;
    protected ImageView mSoundView;
    protected ImageView mSuccessView;
    protected TextView mTipsTopView;
    protected TextView mTipsBottomView;
    protected FaceDetectRoundView mFaceDetectRoundView;
    protected LinearLayout mImageLayout;
    // 人脸信息
    protected FaceConfig mFaceConfig;
    protected ILivenessStrategy mILivenessStrategy;
    // 显示Size
    private Rect mPreviewRect = new Rect();
    protected int mDisplayWidth = 0;
    protected int mDisplayHeight = 0;
    protected int mSurfaceWidth = 0;
    protected int mSurfaceHeight = 0;
    protected Drawable mTipsIcon;
    // 状态标识
    protected volatile boolean mIsEnableSound = true;
    protected HashMap<String, String> mBase64ImageMap = new HashMap<String, String>();
    protected boolean mIsCreateSurface = false;
    protected boolean mIsCompletion = false;
    // 相机
    protected Camera mCamera;
    protected Camera.Parameters mCameraParam;
    protected int mCameraId;
    protected int mPreviewWidth;
    protected int mPreviewHight;
    protected int mPreviewDegree;
    // 监听系统音量广播
    protected BroadcastReceiver mVolumeReceiver;
    TextView tv_title, tv_login_account, tv_to_register;

    public void faceCreat() {
        DisplayMetrics dm = new DisplayMetrics();
        Display display = this.getWindowManager().getDefaultDisplay();
        display.getMetrics(dm);
        mDisplayWidth = dm.widthPixels;
        mDisplayHeight = dm.heightPixels;
        tv_title = (TextView) findViewById(com.baidu.idl.face.platform.ui.R.id.tv_title);
        tv_login_account = (TextView) findViewById(com.baidu.idl.face.platform.ui.R.id.tv_login_account);
        tv_to_register = (TextView) findViewById(com.baidu.idl.face.platform.ui.R.id.tv_to_register);
        FaceSDKResSettings.initializeResId();
        mFaceConfig = FaceSDKManager.getInstance().getFaceConfig();

        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int vol = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        mIsEnableSound = vol > 0 ? mFaceConfig.isSound : false;

        mRootView = this.findViewById(com.baidu.idl.face.platform.ui.R.id.liveness_root_layout);
        mFrameLayout = (FrameLayout) mRootView.findViewById(com.baidu.idl.face.platform.ui.R.id.liveness_surface_layout);

        mSurfaceView = new SurfaceView(this);
        mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.setSizeFromLayout();
        mSurfaceHolder.addCallback(this);
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        int w = mDisplayWidth;
        int h = mDisplayHeight;

        FrameLayout.LayoutParams cameraFL = new FrameLayout.LayoutParams(
                (int) (w * FaceDetectRoundView.SURFACE_RATIO), (int) (h * FaceDetectRoundView.SURFACE_RATIO),
                Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

        mSurfaceView.setLayoutParams(cameraFL);
        mFrameLayout.addView(mSurfaceView);

        mRootView.findViewById(com.baidu.idl.face.platform.ui.R.id.liveness_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        mFaceDetectRoundView = (FaceDetectRoundView) mRootView.findViewById(com.baidu.idl.face.platform.ui.R.id.liveness_face_round);
        mCloseView = (ImageView) mRootView.findViewById(com.baidu.idl.face.platform.ui.R.id.liveness_close);
        mSoundView = (ImageView) mRootView.findViewById(com.baidu.idl.face.platform.ui.R.id.liveness_sound);
        mSoundView.setImageResource(mIsEnableSound ?
                com.baidu.idl.face.platform.ui.R.mipmap.ic_enable_sound_ext : com.baidu.idl.face.platform.ui.R.mipmap.ic_disable_sound_ext);
        mSoundView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mIsEnableSound = !mIsEnableSound;
                mSoundView.setImageResource(mIsEnableSound ?
                        com.baidu.idl.face.platform.ui.R.mipmap.ic_enable_sound_ext : com.baidu.idl.face.platform.ui.R.mipmap.ic_disable_sound_ext);
                if (mILivenessStrategy != null) {
                    mILivenessStrategy.setLivenessStrategySoundEnable(mIsEnableSound);
                }
            }
        });
        mTipsTopView = (TextView) mRootView.findViewById(com.baidu.idl.face.platform.ui.R.id.liveness_top_tips);
        mTipsBottomView = (TextView) mRootView.findViewById(com.baidu.idl.face.platform.ui.R.id.liveness_bottom_tips);
        mSuccessView = (ImageView) mRootView.findViewById(com.baidu.idl.face.platform.ui.R.id.liveness_success_image);

        mImageLayout = (LinearLayout) mRootView.findViewById(com.baidu.idl.face.platform.ui.R.id.liveness_result_image_layout);
        if (mBase64ImageMap != null) {
            mBase64ImageMap.clear();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        MyApp.setFaceConfig();
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        mVolumeReceiver = VolumeUtils.registerVolumeReceiver(this, this);
        if (mTipsTopView != null) {
            mTipsTopView.setText(com.baidu.idl.face.platform.ui.R.string.detect_face_in);
        }
        startPreview();
        if ("2".equals(type)) {
            SPUtils.getInstance(Constant.SP_CONFIG).put(Constant.MUST_VERIFY, true);
        }
    }

    @Override
    public void onBackPressed() {
        SPUtils.getInstance(Constant.SP_CONFIG).put(Constant.MUST_VERIFY, true);
        /*if("1".equals(type) || "2".equals(type)){
            //直接返回到勘探点列表
            ArtUtils.startActivity(new Intent(this, SurveyPointListActivity.class));
        }else {
            super.onBackPressed();
        }*/
        super.onBackPressed();
    }

    public void showLogin(View.OnClickListener clickListener) {
        tv_login_account.setVisibility(View.VISIBLE);
        tv_to_register.setVisibility(View.VISIBLE);
        tv_login_account.setOnClickListener(clickListener);
        tv_to_register.setOnClickListener(clickListener);
    }

    @Override
    public void onPause() {
        super.onPause();
        stopPreview();
    }

    public void setTitle(String rx) {
        tv_title.setText(rx);
    }

    @Override
    public void onStop() {
        if (mILivenessStrategy != null) {
            mILivenessStrategy.reset();
        }
        VolumeUtils.unRegisterVolumeReceiver(this, mVolumeReceiver);
        mVolumeReceiver = null;
        super.onStop();
        stopPreview();
    }


    @Override
    public void volumeChanged() {
        try {
            AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
            if (am != null) {
                int cv = am.getStreamVolume(AudioManager.STREAM_MUSIC);
                mIsEnableSound = cv > 0;
                mSoundView.setImageResource(mIsEnableSound
                        ? com.baidu.idl.face.platform.ui.R.mipmap.ic_enable_sound_ext : com.baidu.idl.face.platform.ui.R.mipmap.ic_disable_sound_ext);
                if (mILivenessStrategy != null) {
                    mILivenessStrategy.setLivenessStrategySoundEnable(mIsEnableSound);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private Camera open() {
        Camera camera;
        int numCameras = Camera.getNumberOfCameras();
        if (numCameras == 0) {
            return null;
        }

        int index = 0;
        while (index < numCameras) {
            Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
            Camera.getCameraInfo(index, cameraInfo);
            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                break;
            }
            index++;
        }

        if (index < numCameras) {
            camera = Camera.open(index);
            mCameraId = index;
        } else {
            camera = Camera.open(0);
            mCameraId = 0;
        }
        return camera;
    }

    protected void startPreview() {
        if (mSurfaceView != null && mSurfaceView.getHolder() != null) {
            mSurfaceHolder = mSurfaceView.getHolder();
            mSurfaceHolder.addCallback(this);
        }

        if (mCamera == null) {
            try {
                mCamera = open();
            } catch (RuntimeException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (mCamera == null) {
            return;
        }

        if (mCameraParam == null) {
            mCameraParam = mCamera.getParameters();
        }

        mCameraParam.setPictureFormat(PixelFormat.JPEG);
        int degree = displayOrientation(this);
        mCamera.setDisplayOrientation(degree);
        // 设置后无效，camera.setDisplayOrientation方法有效
        mCameraParam.set("rotation", degree);
        mPreviewDegree = degree;

        Point point = CameraPreviewUtils.getBestPreview(mCameraParam,
                new Point(mDisplayWidth, mDisplayHeight));

        mPreviewWidth = point.x;
        mPreviewHight = point.y;
        // Preview 768,432

        if (mILivenessStrategy != null) {
            mILivenessStrategy.setPreviewDegree(degree);
        }

        mPreviewRect.set(0, 0, mPreviewHight, mPreviewWidth);

        mCameraParam.setPreviewSize(mPreviewWidth, mPreviewHight);
        mCamera.setParameters(mCameraParam);

        try {
            mCamera.setPreviewDisplay(mSurfaceHolder);
            mCamera.stopPreview();
            mCamera.setErrorCallback(this);
            mCamera.setPreviewCallback(this);
            mCamera.startPreview();
        } catch (RuntimeException e) {
            e.printStackTrace();
            CameraUtils.releaseCamera(mCamera);
            mCamera = null;
        } catch (Exception e) {
            e.printStackTrace();
            CameraUtils.releaseCamera(mCamera);
            mCamera = null;
        }
    }

    protected void stopPreview() {
        if (mCamera != null) {
            try {
                mCamera.setErrorCallback(null);
                mCamera.setPreviewCallback(null);
                mCamera.stopPreview();
            } catch (RuntimeException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                CameraUtils.releaseCamera(mCamera);
                mCamera = null;
            }
        }
        if (mSurfaceHolder != null) {
            mSurfaceHolder.removeCallback(this);
        }
        if (mILivenessStrategy != null) {
            mILivenessStrategy = null;
        }
    }

    private int displayOrientation(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        int rotation = windowManager.getDefaultDisplay().getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
            default:
                degrees = 0;
                break;
        }
        int result = (0 - degrees + 360) % 360;
        if (APIUtils.hasGingerbread()) {
            Camera.CameraInfo info = new Camera.CameraInfo();
            Camera.getCameraInfo(mCameraId, info);
            if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                result = (info.orientation + degrees) % 360;
                result = (360 - result) % 360;
            } else {
                result = (info.orientation - degrees + 360) % 360;
            }
        }
        return result;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        mIsCreateSurface = true;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder,
                               int format,
                               int width,
                               int height) {
        mSurfaceWidth = width;
        mSurfaceHeight = height;
        if (holder.getSurface() == null) {
            return;
        }
        startPreview();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mIsCreateSurface = false;
    }

    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {

        if (mIsCompletion) {
            return;
        }

        if (mILivenessStrategy == null) {
            mILivenessStrategy = FaceSDKManager.getInstance().getLivenessStrategyModule();
            mILivenessStrategy.setPreviewDegree(mPreviewDegree);
            mILivenessStrategy.setLivenessStrategySoundEnable(mIsEnableSound);

            Rect detectRect = FaceDetectRoundView.getPreviewDetectRect(
                    mDisplayWidth, mPreviewHight, mPreviewWidth);
            mILivenessStrategy.setLivenessStrategyConfig(
                    mFaceConfig.getLivenessTypeList(), mPreviewRect, detectRect, this);
        }
        mILivenessStrategy.livenessStrategy(data);
    }

    @Override
    public void onError(int error, Camera camera) {
    }

    private void onRefreshView(FaceStatusEnum status, String message) {
        switch (status) {
            case OK:
            case Liveness_OK:
            case Liveness_Completion:
                onRefreshTipsView(false, message);
                mTipsBottomView.setText("");
                mFaceDetectRoundView.processDrawState(false);
                onRefreshSuccessView(true);
                break;
            case Detect_DataNotReady:
            case Liveness_Eye:
            case Liveness_Mouth:
            case Liveness_HeadUp:
            case Liveness_HeadDown:
            case Liveness_HeadLeft:
            case Liveness_HeadRight:
            case Liveness_HeadLeftRight:
                onRefreshTipsView(false, message);
                mTipsBottomView.setText("");
                mFaceDetectRoundView.processDrawState(false);
                onRefreshSuccessView(false);
                break;
            case Detect_PitchOutOfUpMaxRange:
            case Detect_PitchOutOfDownMaxRange:
            case Detect_PitchOutOfLeftMaxRange:
            case Detect_PitchOutOfRightMaxRange:
                onRefreshTipsView(true, message);
                mTipsBottomView.setText(message);
                mFaceDetectRoundView.processDrawState(true);
                onRefreshSuccessView(false);
                break;
            default:
                onRefreshTipsView(false, message);
                mTipsBottomView.setText("");
                mFaceDetectRoundView.processDrawState(true);
                onRefreshSuccessView(false);
        }
    }

    public void setTips(String x) {
        mTipsTopView.setText(x);
    }

    private void onRefreshTipsView(boolean isAlert, String message) {
        if (isAlert) {
            if (mTipsIcon == null) {
                mTipsIcon = getResources().getDrawable(com.baidu.idl.face.platform.ui.R.mipmap.ic_warning);
                mTipsIcon.setBounds(0, 0, (int) (mTipsIcon.getMinimumWidth() * 0.7f),
                        (int) (mTipsIcon.getMinimumHeight() * 0.7f));
                mTipsTopView.setCompoundDrawablePadding(15);
            }
            mTipsTopView.setBackgroundResource(com.baidu.idl.face.platform.ui.R.drawable.bg_tips);
            mTipsTopView.setText(com.baidu.idl.face.platform.ui.R.string.detect_standard);
            mTipsTopView.setCompoundDrawables(mTipsIcon, null, null, null);
        } else {
            mTipsTopView.setBackgroundResource(com.baidu.idl.face.platform.ui.R.drawable.bg_tips_no);
            mTipsTopView.setCompoundDrawables(null, null, null, null);
            if (!TextUtils.isEmpty(message)) {
                mTipsTopView.setText(message);
            }
        }
    }

    private void onRefreshSuccessView(boolean isShow) {
        if (mSuccessView.getTag() == null) {
            Rect rect = mFaceDetectRoundView.getFaceRoundRect();
            RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) mSuccessView.getLayoutParams();
            rlp.setMargins(
                    rect.centerX() - (mSuccessView.getWidth() / 2),
                    rect.top - (mSuccessView.getHeight() / 2),
                    0,
                    0);
            mSuccessView.setLayoutParams(rlp);
            mSuccessView.setTag("setlayout");
        }
        mSuccessView.setVisibility(isShow ? View.VISIBLE : View.INVISIBLE);
    }

    private void saveImage(HashMap<String, String> imageMap) {
        Set<Map.Entry<String, String>> sets = imageMap.entrySet();
        Bitmap bmp = null;
        mImageLayout.removeAllViews();
        for (Map.Entry<String, String> entry : sets) {
            bmp = base64ToBitmap(entry.getValue());
            ImageView iv = new ImageView(this);
            iv.setImageBitmap(bmp);
            mImageLayout.addView(iv, new LinearLayout.LayoutParams(300, 300));
        }
    }

    public static Bitmap base64ToBitmap(String base64Data) {
        byte[] bytes = Base64Utils.decode(base64Data, Base64Utils.NO_WRAP);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return 0;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

    }
}
